//
//  TFTextFieldView.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/4/24.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

@objc enum TFChatAreaStatus: Int  {
    //默认是不开启互动区域
    case AllNone
    //只开启聊天
    case Chat
    //只开启提问
    case Ask
    //两者都有
    case AskAndChat
 
}
typealias TFTextFieldViewSendBlock = (_ textView:TF_TextView) -> Void
typealias TFTextFieldViewClickBlock = (_ isClick:Bool) -> Void

typealias  TFTextFieldViewKeyboardWillShowBlock = (_ height:CGFloat) -> Void

class TFTextFieldView: UIView, UITextViewDelegate {

    @objc public let textView = TF_TextView()
    @objc public var sendBlock: TFTextFieldViewSendBlock?

    @objc public var keyboardWillShowBlock: TFTextFieldViewKeyboardWillShowBlock?
    //聊天图片
    @objc public let inputImg = UIImageView()
    //聊天框的背景图
    @objc public let fieldView = UIView()
    //表情按键
    @objc public let expressionButton = UIButton()
    @objc public let askButton = UIButton()
    //更多
    @objc public let moreButton = UIButton()
    //禁言提示
    @objc public let disabelChat = UILabel()
    @objc public var isShowMoreView:Bool = false
    //点击了表情
    @objc public var expresssionClick:Bool = false
    //是否提问  Yes 为ask
    @objc public var isChat:Bool = false
    //记住TF_TextFieldView的高度
    @objc public var superHeight:CGFloat = 0
    //true为禁言;false为解除禁言
    @objc public var isAbleChat:Bool = false
    
    @objc public var status:TFChatAreaStatus = .AllNone
    var placeholder:NSString = ""
    let lineView = UIView()
    var textViewY:CGFloat = 0
    var keyBoardHight:CGFloat = 0
    var originalFrame:CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
    var lastText:NSString = ""
    // 是否更新了textview;
    var isupadteTetxview:Bool = false
    //记住输入框的高度;
    var fieldRect:CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
    // 记住输入文字,隐藏更多按钮
    var isInput:Bool = false
    var isOrientationiPhoneX:CGFloat = 0
    // 聊天区域的提问
    var ischatAsk:Bool = false
    var maxHeight:CGFloat = 80.0
    
    var keyboardFrameEnd:CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
    

    //显示键盘
    @objc func keyboardWillShow(noti:NSNotification) {

           //不是聊天不用处理
        if (self.currentTextView(self.textView) == true) {
           
            let keyboardInfo:NSDictionary = noti.userInfo! as NSDictionary
            
                let keyboardFrameEnd:NSValue = keyboardInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
            
            let frame:CGRect = keyboardFrameEnd.cgRectValue
            
                
            let animationDuration:NSNumber = keyboardInfo.value(forKey: UIResponder.keyboardAnimationDurationUserInfoKey) as! NSNumber
                //  执行动画
            let duration = animationDuration.floatValue

            var aa:CGFloat = 56
            if self.frame.height>aa {
                aa = self.frame.height
            }
           // 修改底部约束
            let  chatBarY:CGFloat = TalkfunSharedTools.getMainScreen().size.height - frame.size.height - aa
                
            self.keyboardFrameEnd = frame
                
            UIView.animate(withDuration: TimeInterval(duration)) {
                    self.frame = CGRect(x: 0, y: chatBarY, width:  self.frame.size.width, height: aa)
                }

            }
        
      
        
    }
    
    override var frame: CGRect
    {
        didSet{
        
            if(self.keyboardWillShowBlock != nil)
            {

                var ha = frame.size.height-56
                if ha<5 {
                    ha = 0
                }
                var height:CGFloat = ha+self.keyboardFrameEnd.height
                
                if height<0 {
                    height = 0
                }
                self.keyboardWillShowBlock!(height)

                
                
            }
            
        }
        
        
    }
    //隐藏键盘
    @objc func KeyboardWillHide(noti:NSNotification) {
        

           //不是聊天不用处理
        if (self.currentTextView(self.textView) == true) {
              
                let keyboardInfo:NSDictionary = noti.userInfo! as NSDictionary
                
                let animationDuration:NSNumber = keyboardInfo.value(forKey: UIResponder.keyboardAnimationDurationUserInfoKey) as! NSNumber
                //  执行动画
                let duration = animationDuration.floatValue
                
                let  chatBarY:CGFloat = TalkfunSharedTools.getMainScreen().size.height - self.frame.size.height-self.isOrientationiPhoneX
                
                self.keyboardFrameEnd = CGRect(x: 0, y: 0, width: 0, height: 0)
                UIView.animate(withDuration: TimeInterval(duration)) {
                    self.frame = CGRect(x: 0, y: chatBarY, width:  self.frame.size.width, height: self.frame.size.height)
                }

          
        }
        
     
          
      
    }
    @objc public func destroySharedIntance()
    {
        NotificationCenter.default.removeObserver(self)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        //键盘显示前
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil)

        //键盘隐藏前
        NotificationCenter.default.addObserver(self, selector: #selector(self.KeyboardWillHide(noti:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        self.originalFrame = frame
        self.isOrientationiPhoneX = 0
        if (self.isNotchScreen) {
          
            self.isOrientationiPhoneX = 21
            
        }
        self.backgroundColor = UIColor.white
        self.fieldView.backgroundColor = UIColor(red: 244/255.0, green: 246/255.0, blue: 249/255.0, alpha: 1)
        self.fieldView.layer.cornerRadius = 20
        self.fieldView.layer.masksToBounds = true
        self.addSubview(self.fieldView)
        
        self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_chat")
        self.fieldView.addSubview(self.inputImg)
        

        self.textView.delegate            = self;

        self.textView.backgroundColor     = UIColor.clear
        
        self.textView.font                = UIFont.PingFang(size: 16)
        self.textView.layer.cornerRadius  = 5
        self.textView.layer.masksToBounds = true
        self.textView.returnKeyType       = .send
      
        self.textView.layoutManager.allowsNonContiguousLayout = false
        self.fieldView.addSubview(self.textView)
        
        self.disabelChat.textAlignment = .center
        self.disabelChat.textColor = UIColor(red: 150/255.0, green: 160/255.0, blue: 170/255.0, alpha: 1)
        
        self.disabelChat.font = UIFont.PingFang(size: 16)
        self.disabelChat.isHidden = true;
        self.fieldView.addSubview(self.disabelChat)
        
        self.expressionButton.setImage(UIImage.init(named: "HTLive.bundle/toolbar_imoji"), for: .normal)
        self.expressionButton.setImage(UIImage.init(named: "HTLive.bundle/imoji"), for: .selected)
        self.addSubview(self.expressionButton)
        
        self.askButton.setImage(UIImage.init(named: "HTLive.bundle/toolbar_ask_green"), for: .normal)
        self.askButton.setImage(UIImage.init(named: "HTLive.bundle/toolbar_chat_green"), for: .selected)
        self.addSubview(self.askButton)
        
        self.moreButton.setImage(UIImage.init(named: "HTLive.bundle/toolbar_more"), for: .normal)

        self.addSubview(self.moreButton)
        
        self.lineView.backgroundColor = UIColor(red:242/255.0 , green: 242/255.0, blue: 242/255.0, alpha: 1)
        self.isChat = true
  
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //修改输入框  禁言 isable
  @objc public func takeChatandAsk()
  {
      
      if (self.status == .AllNone) {//两者都没有
            self.fieldView.isHidden = true
            self.expressionButton.isHidden = true
            self.askButton.isHidden = true
           
      } else if (self.status == .Chat) {//只有聊天区域
            self.fieldView.isHidden = false
            self.expressionButton.isHidden = false
            self.askButton.isHidden = false
            self.askButton.isUserInteractionEnabled = false
            if (self.isAbleChat) {
                self.askButton.isHidden = true
                self.expressionButton.isHidden = true
                self.disabelChat.isHidden = false
                self.inputImg.isHidden = true
                self.textView.isHidden = true
            } else {
                if (self.isChat) {
                    
                    if (self.askButton.isSelected) {
                        self.askButton.setImage(UIImage.init(named: "HTLive.bundle/toolbar_chat_green"), for: .normal)
                        
                        self.placeholder = "说说你的问题..."
                        self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_ask")
                       
                        self.expressionButton.isHidden = true
                    } else {
                        self.askButton.setImage(UIImage.init(named: "HTLive.bundle/toolbar_ask_green"), for: .normal)
                       
                        self.placeholder = "说点什么吧..."
                        self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_chat")
       
                        self.expressionButton.isHidden = false
                    }
                  
                    self.moreButton.isHidden = false
                    self.askButton.isHidden = true

                    self.disabelChat.isHidden = true
                    self.inputImg.isHidden = false
                    self.textView.isHidden = false
                } else {
                    self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_ask")
                    self.moreButton.isHidden = false
                    self.askButton.isHidden = true
                    self.expressionButton.isHidden = true
                    self.placeholder = "说说你的问题..."
                    
                    self.disabelChat.isHidden = true
                    self.inputImg.isHidden = true
                    self.textView.isHidden = true
                    self.fieldView.isHidden = true
                    
                }
               
            }
           }
        else if (self.status == .Ask) {//只有提问区域
         
            //是否在禁言
            if (self.isAbleChat) {
                self.fieldView.isHidden = false
                self.askButton.isHidden = true
                self.expressionButton.isHidden = true
                //区别是聊天还是提问区域
                if (self.isChat) {
                    self.fieldView.isHidden = true
                    self.disabelChat.isHidden = false
                    self.inputImg.isHidden = true

                    self.textView.isHidden = true
                   
                } else {
                    self.textView.isHidden = false
                    self.disabelChat.isHidden = true
                    self.inputImg.isHidden = false
                    self.placeholder = "说说你的问题..."
                    self.textView.tf_placeholder = self.placeholder as String
                    self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_ask")
                    
                }
              
            }else
            {
                //切到到了聊天
                if (self.isChat) {
                    
                    
                    self.askButton.isHidden = true
                    self.fieldView.isHidden = true
                    self.expressionButton.isHidden = true
                    
                   
                } else
                {
                    
                    self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_ask")
                    self.askButton.isHidden = true
                    self.expressionButton.isHidden = true
                    self.fieldView.isHidden = false
                    self.placeholder = "说说你的问题..."
                    self.textView.tf_placeholder = self.placeholder as String
                    

                }
            }
           
            
        } else if (self.status == .AskAndChat) {//两者都有
            
            self.fieldView.isHidden = false
            self.expressionButton.isHidden = false
            self.askButton.isHidden = false
            self.askButton.isUserInteractionEnabled = true
            //是否在禁言
            if (self.isAbleChat) {
                self.askButton.isHidden = true
                self.expressionButton.isHidden = true
                //区别是聊天还是提问区域
                if (self.isChat) {
                    self.disabelChat.isHidden = false
                    self.inputImg.isHidden = true

                    self.textView.isHidden = true
                } else {
                    self.textView.isHidden = false
                    self.disabelChat.isHidden = true
                    self.inputImg.isHidden = false
                    self.placeholder = "说说你的问题..."
                    self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_ask")
                    
                }
                self.layoutSubviews()
            } else {
                if (self.isChat) {
                    
                    if (self.askButton.isSelected) {
                        self.askButton.setImage(UIImage.init(named: "HTLive.bundle/toolbar_chat_green"), for: .normal)
                       
                        self.placeholder = "说说你的问题..."
                        self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_ask")
                        self.expressionButton.isHidden = true
                    } else {
                        self.askButton.setImage(UIImage.init(named: "HTLive.bundle/toolbar_ask_green"), for: .normal)
           
                        self.placeholder = "说点什么吧..."
                        self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_chat")
                        self.expressionButton.isHidden = false
                    }
                  
                  
                    self.askButton.isHidden = false
                  
                } else {
                    self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_ask")
                   
                    self.askButton.isHidden = true
                    self.expressionButton.isHidden = true
                    self.placeholder = "说说你的问题..."
                    
                }
                self.disabelChat.isHidden = true
                self.inputImg.isHidden = false
                self.textView.isHidden = false
            }
        }
        
        

        if (self.expresssionClick||self.isInput) {  //表情包的点击
            self.moreButton.isHidden = true
        } else {
            if (self.isChat) {
                self.moreButton.isHidden = false
            }else
            {
                //在提问页不用更用
                self.moreButton.isHidden = true
            }
            
        }
        
        if (self.moreButton.isHidden) {
            self.moreButton.frame = CGRect(x: self.frame.size.width, y: 8, width: 40, height: 40)
            self.moreButton.isHidden = true;
        } else {
            self.moreButton.frame = CGRect(x: self.frame.size.width-51, y: 8, width: 40, height: 40)

            self.moreButton.isHidden = false;
        }
        if (self.askButton.isHidden) {
            self.askButton.frame = self.moreButton.frame;
        } else {
            self.askButton.frame = CGRect(x: self.moreButton.frame.origin.x-6-40, y: 8, width: 40, height: 40)
            
        }
         
        if (self.expressionButton.isHidden) {
            self.expressionButton.frame = self.askButton.frame;
        } else {
            self.expressionButton.frame = CGRect(x: self.askButton.frame.origin.x-40-6, y: 8, width: 40, height: 40)
  
        }
       
        
       
        if (self.isupadteTetxview == false) {
            self.fieldView.frame = CGRect(x: 12, y: 8, width: self.expressionButton.frame.origin.x-13-12, height: 40)
        } else {

            self.fieldView.frame = CGRect(x: self.fieldRect.origin.x, y: self.fieldRect.origin.y, width: self.expressionButton.frame.origin.x-13-12, height: self.fieldRect.size.height)
            
        }
        
         let textViewX:CGFloat = 36
         let textViewW:CGFloat = self.fieldView.frame.size.width-textViewX-5
         let textViewH:CGFloat = self.fieldView.frame.size.height - 4
         let textViewY:CGFloat = (self.fieldView.frame.size.height-textViewH)*0.5
         
         self.textView.frame = CGRect(x: textViewX, y: textViewY, width: textViewW, height: textViewH)
         self.textViewY        = textViewY;
         self.lineView.frame = CGRect(x: 0, y: self.fieldView.frame.maxY+8, width: self.frame.size.width, height: 1)

         self.inputImg.frame = CGRect(x: 12, y: 10, width: 20, height: 20)
     
        self.disabelChat.frame = self.fieldView.bounds;
        
    }

    
    override func layoutSubviews() {
        super.layoutSubviews()
    
        self.textView.tf_placeholder = self.placeholder as String
     
    }
    
   // #pragma mark - == UITextViewDelegate
    
    func textViewDidBeginEditing(_ textView: UITextView) {

        self.lastText = ""
        

        self.textView.tf_placeholder = self.placeholder as String
        
        if (self.isChat) {
            if (self.fieldRect.size.height > 0) {
                self.isupadteTetxview = true
            }
        } else {
            if (self.fieldRect.size.height > 0) {
                self.isupadteTetxview = false
            }
        }
        
        self.isInput = true
        
        self.takeChatandAsk()
        
    }
    
    func textViewDidChange(_ textView: UITextView) {


        let frame = textView.frame
       
        let constraintSize =  CGSize(width: frame.size.width, height: CGFloat(MAXFLOAT))
        
        var size = textView.sizeThatFits(constraintSize)
       
        
        if (size.height<=frame.size.height) {
           
        }else{
            if (size.height>=maxHeight){
                size.height = maxHeight
                textView.isScrollEnabled = true  // 允许滚动
            }else{
                textView.isScrollEnabled = false   // 不允许滚动
            }
        }
        
        textView.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: size.height)
       
        self.fieldView.frame = CGRect(x: 12, y: 8, width: frame.size.width+41, height: size.height+4)

        self.fieldRect = self.fieldView.frame
        
        let superHeight:CGFloat = self.fieldView.frame.maxY+8
      
        
        
        
        UIView.animate(withDuration: 0) {
            self.frame = CGRect(x: self.frame.origin.x, y: UIScreen.main.bounds.height-(self.keyboardFrameEnd.height+superHeight), width: self.frame.size.width, height: superHeight)
            
        }
        
        self.superHeight = superHeight;
        self.lineView.frame = CGRect(x: 0, y: superHeight-1, width: self.frame.size.width, height: 1)
     
        let size_H = TalkfunSharedTools.getSizeLabel(labelString: NSMutableAttributedString.init(string: textView.text), labelWidth: self.fieldView.frame.width-40, labelfont: UIFont.systemFont(ofSize: 17))


        if (textView.text.count > self.lastText.length+5) {
            if (size_H.height>maxHeight) {
                textView.setContentOffset(CGPoint(x: 0, y: (size_H.height-maxHeight)), animated: false)

            }
        }

        self.lastText = textView.text! as NSString
        
       
    }
    @objc public func udateFrame(height: CGFloat,textView:UITextView)
    {
        let frame = textView.frame
       
        let constraintSize = CGSize(width: frame.size.width, height: CGFloat(MAXFLOAT))
        
        var size = textView.sizeThatFits(constraintSize)
       
        
        if (size.height<=frame.size.height) {

        }else{
            if (size.height>=maxHeight){
                size.height = maxHeight;
                textView.isScrollEnabled = true;   // 允许滚动
            }else{
                textView.isScrollEnabled = false;    // 不允许滚动
            }
        }
        
        textView.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: size.height)
        

        self.fieldView.frame = CGRect(x: 12, y: 8, width: frame.size.width+41, height: size.height+4)
    
        self.fieldRect = self.fieldView.frame
        let superHeight:CGFloat = self.fieldView.frame.maxY+8
       
        
        
        UIView.animate(withDuration: 0) {
            self.frame = CGRect(x: self.frame.origin.x, y: UIScreen.main.bounds.height-(height+superHeight)-self.isOrientationiPhoneX, width: self.frame.size.width, height: superHeight)
           
        }
        
        self.superHeight = superHeight;
        self.lineView.frame = CGRect(x: 0, y: superHeight-1, width: self.frame.size.width, height: 1)
   

        
        let size_H = TalkfunSharedTools.getSizeLabel(labelString: NSMutableAttributedString.init(string: textView.text), labelWidth: self.fieldView.frame.width-40, labelfont: UIFont.systemFont(ofSize: 17))
        


        if (textView.text.count > self.lastText.length+5) {
            if (size_H.height>maxHeight) {
                textView.setContentOffset(CGPoint(x: 0, y: (size_H.height-maxHeight)), animated: false)
              
            }
        }

        self.lastText = textView.text! as NSString
        
       
    }
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
 
        if text == "\n" {
            
            let whiteSpace = NSCharacterSet.whitespacesAndNewlines
            
            let str =   NSString.init(string: textView.text).trimmingCharacters(in: whiteSpace)
            

            if (str.count != 0) {
       
                if self.sendBlock != nil {
        
                    self.sendBlock!(self.textView)

                    self.superHeight = 0;
                    self.fieldRect = .zero;
                    self.isInput = false;
                    self.textView.resignFirstResponder()
                    
                  
                    self.textView.tf_placeholder = self.placeholder as String
                    }
                
                
            }
            return false
        }
        return true
    }


    //textViewDidEndEditing
    func textViewDidEndEditing(_ textView: UITextView) {
        
        if (textView.text.count > 0) {
            self.isupadteTetxview = true
            self.isInput = true;
           
        } else {
            self.isupadteTetxview = false
            self.moreButton.isSelected = false
            self.isInput = false
            
            
        }

        self.takeChatandAsk()
    }
    
}
